/**
  * @Author: songgh
  * @Date: 2021-09-20 14:41:08
  * @LastEditors: songgh
  * @LastEditTime: 2021-09-20 15:41:08
  * @Description: 打包后启动 server
  */

const mime = require('mime');
const http = require('http');
const querystring = require('querystring');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
    const { method } = req;

    // 请求类型
    switch (method) {
        case "GET":
            get(req, res);
            break;
        case "POST":
            post(req, res);
            break;
        default:
            res.end();
            break;
    }
});

function get(req, res) {
    const [url, paramsStr] = req.url.split(/\?/);
    const params = querystring.parse(paramsStr);

    const filepath = path.resolve(__dirname, `./planner/${url}`);
    const type = mime.getType(filepath);
    res.writeHeader(200,{
        'content-type':type
    });

    // 加载静态文件
    if (/\.(js|css|json)$/.test(url)) {
        res.end(fs.readFileSync(filepath, { encoding: 'utf-8' }));
        return;
    }

    if (/\.(png|jpeg|jpg|svg)$/.test(url)) {
        res.end(fs.readFileSync(path.resolve(filepath)));
        return;
    }

    res.writeHeader(200,{
        'content-type':''
    });
    const html = fs.readFileSync('./planner/index.html', { encoding: 'utf-8' });
    res.end(html);
}

function post(req, res) {
    const { url } = req;

    // 接收 POST 的数据
    let postData = '';
    req.on('data', chunk => {
        postData += chunk;
    });

    req.on('end', () => {
        if (postData) {
            const params = JSON.parse(postData)

            switch (url) {
                case '/':
                    res.end();
                    break;

                default:
                    res.statusCode = 403;
                    res.end();
                    break;
            }

        }
    });
}

server.listen(3000, () => {
    console.log('http://localhost:3000/');
    console.log('http://127.0.0.1:3000/');
})